package com.app.xinfadi.ui;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.support.design.widget.NavigationView;
import android.support.design.widget.Snackbar;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.widget.Toolbar;
import android.view.KeyEvent;
import android.view.MenuItem;
import android.view.View;
import android.widget.TextView;

import com.app.xinfadi.R;
import com.app.xinfadi.base.BaseActivity;
import com.app.xinfadi.ui.center_role_purchase_plan.CenterRolePurchasePlanFragment;
import com.app.xinfadi.ui.home.HomeFragment;
import com.app.xinfadi.ui.lead_role_ourchase_plan.LeadRoleExamineAndApproveListFragment;
import com.app.xinfadi.ui.purchase_plan.PurchasePlanFragment;
import com.app.xinfadi.ui.purchase_price.PurchasePriceFragment;
import com.app.xinfadi.ui.user.UserModifyPwdActivity;
import com.app.xinfadi.ui.user.UserSettingActivity;
import com.app.xinfadi.util.LogUtil;
import com.app.xinfadi.util.SharedPreferencesUtil;
import com.app.xinfadi.util.VersionUpdateUtil;
import com.app.xinfadi.widget.sliding_tab.SlidingTabLayout;

import java.util.Timer;
import java.util.TimerTask;

public class MainActivity extends BaseActivity {
    public static final String MESSAGE_RECEIVED_ACTION = "com.app.xinfadi.ui.MainAcitivity.MESSAGE_RECEIVED_ACTION";
    private static final String EXITACTION = "action.exit";

    private static final String TAG = MainActivity.class.getSimpleName();
    private MainMessageReceiver mMainMessageReceiver;
    private HomeFragment homeFragment;
    private PurchasePlanFragment purchasePlanFragment;
    private PurchasePriceFragment purchasePriceFragment;
    private CenterRolePurchasePlanFragment centerRolePurchasePlanFragment;
    private LeadRoleExamineAndApproveListFragment leadRoleExamineAndApproveListFragment;
    private TextView homepageTv;
    private TextView purchasePlanTv;
    private static boolean isExit = false;
    private final static int HOME = 0;
    private final static int PURCHASE_PLAN = 1;
    private final static int PURCHASE_PRICE = 2;
    private final static int CENTER_ROLE_PURCHASE_PLAN = 3;
    private final static int LEAD_ROLE_EXAMINE_AND_APPROVE_LIST = 4;

    private MyTimerTask myTimerTask;
    private View appbar;
    private TextView title;
    public SlidingTabLayout mSlidingTabLayout;
    public SlidingTabLayout sliding_tabs_center_role;
    private NavigationView nav_view;
    private DrawerLayout drawerLayout;
    private View headerView;
    private TextView user_nickname;
    private TextView purchasePriceTv;
    //当前角色
    private int current_role = 0;
    private TextView centerRolePurchasePlanTv;
    private TextView leadRoleExamineAndApproveListTv;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (savedInstanceState != null) {
            savedInstanceState.putParcelable("android:support:fragments", null);
        }
        setContentView(R.layout.activity_main);
        initToolbar();
        getBundleData();
        initView();
        initData();
        current_role = Integer.valueOf(SharedPreferencesUtil.getInstance().getUserRole());
        if (current_role==0){
            purchasePlanTv.setVisibility(View.VISIBLE);
            setTabSelection(HOME);
        }else if(current_role==1){
            centerRolePurchasePlanTv.setVisibility(View.VISIBLE);
            setTabSelection(HOME);
        }else if(current_role==2){
            leadRoleExamineAndApproveListTv.setVisibility(View.VISIBLE);
            homepageTv.setVisibility(View.GONE);
            setTabSelection(LEAD_ROLE_EXAMINE_AND_APPROVE_LIST);
        }
    }

    private void getBundleData() {

    }

    private void initView() {
        homepageTv = (TextView) findViewById(R.id.homepageTv);
        purchasePlanTv = (TextView) findViewById(R.id.purchasePlanTv);
        purchasePriceTv = (TextView) findViewById(R.id.purchasePriceTv);
        centerRolePurchasePlanTv = (TextView) findViewById(R.id.centerRolePurchasePlanTv);
        leadRoleExamineAndApproveListTv = (TextView) findViewById(R.id.leadRoleExamineAndApproveListTv);
        homepageTv.setOnClickListener(this);
        purchasePlanTv.setOnClickListener(this);
        purchasePriceTv.setOnClickListener(this);
        centerRolePurchasePlanTv.setOnClickListener(this);
        leadRoleExamineAndApproveListTv.setOnClickListener(this);
        mSlidingTabLayout = (SlidingTabLayout) findViewById(R.id.sliding_tabs);
        sliding_tabs_center_role = (SlidingTabLayout) findViewById(R.id.sliding_tabs_center_role);
        nav_view = (NavigationView) findViewById(R.id.nav_view);
        drawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
        headerView = findViewById(R.id.rl_user_headface);
        user_nickname = (TextView) headerView.findViewById(R.id.user_nickname);
        user_nickname.setText(SharedPreferencesUtil.getInstance().getUserLoginName());
        nav_view.setNavigationItemSelectedListener(new NavigationView.OnNavigationItemSelectedListener() {
            @Override
            public boolean onNavigationItemSelected(MenuItem menuItem) {
                menuItem.setChecked(true);
                boolean isCloseLayout = true;
                switch (menuItem.getItemId()) {
                    case R.id.nav_password:
                        Intent intent = new Intent(context, UserModifyPwdActivity.class);
                        intent.putExtra("witch_page", 1);
                        startActivity(intent);
                        break;
                    case R.id.nav_setting:
                        Intent intent1 = new Intent(context, UserSettingActivity.class);
                        startActivity(intent1);
                        break;
                }
                if (isCloseLayout)
                    drawerLayout.closeDrawers();
                return false;
            }
        });

    }

    private void initData() {
//        FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
//        homeFragment = getHomeFragment(transaction);
//        purchasePlanFragment = getPurchasePlanFragment(transaction);
//        centerRolePurchasePlanFragment = getCenterRolePurchasePlanFragment(transaction);
//        purchasePriceFragment = getPurchasePriceFragment(transaction);
//        leadRoleExamineAndApproveListFragment = getLeadRoleExamineAndApproveListFragment(transaction);
//        transaction.commit();
    }

    private void initToolbar() {
        appbar = findViewById(R.id.appbar);
        mToolbar = (Toolbar) findViewById(R.id.toolbar);
        mToolbar.setTitle("");
        setSupportActionBar(mToolbar);
        title = (TextView) findViewById(R.id.titleTv);
        title.setVisibility(View.VISIBLE);
        title.setText(context.getString(R.string.app_name));
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
        if (id == R.id.action_settings) {
            return true;
        }
        switch (item.getItemId()) {
            case android.R.id.home:
//                drawerLayout.openDrawer(drawerLayout);
                drawerLayout.openDrawer(GravityCompat.START);
                return true;
        }
        return super.onOptionsItemSelected(item);
    }

    @Override
    public void onClick(View v) {
        super.onClick(v);
        switch (v.getId()) {
            case R.id.homepageTv:
                setTabSelection(HOME);
                break;
            case R.id.purchasePriceTv:
                setTabSelection(PURCHASE_PRICE);
                break;
            case R.id.purchasePlanTv:
                setTabSelection(PURCHASE_PLAN);
                break;

            case R.id.centerRolePurchasePlanTv:
                setTabSelection(CENTER_ROLE_PURCHASE_PLAN);
                break;
            case R.id.leadRoleExamineAndApproveListTv:
                setTabSelection(LEAD_ROLE_EXAMINE_AND_APPROVE_LIST);
                break;
        }
    }

    @Override
    public boolean onKeyDown(int keyCode, android.view.KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            // exitDialog();
            if (isExit == false) {
                isExit = true;
                Snackbar.make(mToolbar, "再按一次退出程序", Snackbar.LENGTH_SHORT).show();
                if (mExitTimer != null)
                    if (myTimerTask != null) {
                        myTimerTask.cancel();
                    }
                myTimerTask = new MyTimerTask();
                mExitTimer.schedule(myTimerTask, 2000);
            } else {
                exitPorgress();
//                android.os.Process.killProcess(android.os.Process.myPid());  //获取PID
//                System.exit(0);
            }

        }
        return false;
    }

    Timer mExitTimer = new Timer();

    class MyTimerTask extends TimerTask {
        @Override
        public void run() {
            isExit = false;
        }
    }

    public void setTabSelection(int index) {
        clearSelection();
        FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
        hideFragments(transaction);
        appbar.setVisibility(View.VISIBLE);
        sliding_tabs_center_role.setVisibility(View.GONE);
        mSlidingTabLayout.setVisibility(View.GONE);

        switch (index) {
            case HOME:
                getSupportActionBar().setDisplayHomeAsUpEnabled(true);
                mToolbar.setNavigationIcon(R.drawable.user_toolbar_img);
                homepageTv.setSelected(true);
                if (homeFragment == null) {
                    homeFragment = getHomeFragment(transaction);
                } else {
                    transaction.show(homeFragment);
                }
                title.setText(context.getString(R.string.app_name));
                title.setVisibility(View.VISIBLE);


                break;
            case PURCHASE_PLAN:
                getSupportActionBar().setDisplayHomeAsUpEnabled(false);

                purchasePlanTv.setSelected(true);
                if (purchasePlanFragment == null) {
                    purchasePlanFragment = getPurchasePlanFragment(transaction);
                } else {
                    transaction.show(purchasePlanFragment);
                }
                appbar.setVisibility(View.VISIBLE);
                title.setText("采购计划");
                title.setVisibility(View.GONE);
                mSlidingTabLayout.setVisibility(View.VISIBLE);

                break;
            case PURCHASE_PRICE:
                getSupportActionBar().setDisplayHomeAsUpEnabled(false);
                purchasePriceTv.setSelected(true);
                if (purchasePriceFragment == null) {
                    purchasePriceFragment = getPurchasePriceFragment(transaction);
                } else {
                    transaction.show(purchasePriceFragment);
                }
                title.setText("报价单");
                title.setVisibility(View.VISIBLE);
                break;
            case CENTER_ROLE_PURCHASE_PLAN:
                getSupportActionBar().setDisplayHomeAsUpEnabled(false);

                centerRolePurchasePlanTv.setSelected(true);
                if (centerRolePurchasePlanFragment == null) {
                    centerRolePurchasePlanFragment = getCenterRolePurchasePlanFragment(transaction);
                } else {
                    transaction.show(centerRolePurchasePlanFragment);
                }
                title.setText("采购计划");
                title.setVisibility(View.GONE);
                sliding_tabs_center_role.setVisibility(View.VISIBLE);
                break;
            case LEAD_ROLE_EXAMINE_AND_APPROVE_LIST:
                mToolbar.setNavigationIcon(R.drawable.user_toolbar_img);
                leadRoleExamineAndApproveListTv.setSelected(true);
                if (leadRoleExamineAndApproveListFragment == null) {
                    leadRoleExamineAndApproveListFragment = getLeadRoleExamineAndApproveListFragment(transaction);
                } else {
                    transaction.show(leadRoleExamineAndApproveListFragment);
                }
                title.setText("采购计划");
                title.setVisibility(View.VISIBLE);
                break;
        }
//        transaction.commit();
        transaction.commitAllowingStateLoss();
    }

    private void updateVersion() {
        VersionUpdateUtil um = new VersionUpdateUtil(context, 0);
        um.isNeedUpdate();
    }

    public void registerMessageReceiver() {
        mMainMessageReceiver = new MainMessageReceiver();
        IntentFilter filter = new IntentFilter();
        filter.setPriority(IntentFilter.SYSTEM_HIGH_PRIORITY);
        filter.addAction(MESSAGE_RECEIVED_ACTION);
        context.registerReceiver(mMainMessageReceiver, filter);
    }

    /**
     * 接受推动消息
     *
     * @author wtf
     */
    public class MainMessageReceiver extends BroadcastReceiver {

        @Override
        public void onReceive(Context context, Intent intent) {
            if (MESSAGE_RECEIVED_ACTION.equals(intent.getAction())) {
                LogUtil.d(TAG, "system 接收到广播");
                // UnReadNewNumber();
            }
// else if (MESSAGE_READ_ALL_ACTION.equals(intent.getAction())) {
//                // 判断
//                LogUtil.v(TAG, "接收到 所有消息已读广播");
//                // news_square_system_number.setVisibility(View.GONE);
//            } else if (MESSAGE_EXIT.equals(intent.getAction())) {
//                LogUtil.d(TAG, "退出");
//                setTabSelection(HOME);
//                user_state = SharedPreferencesUtil.getInstance().getUserState();
//            } else if (MESSAGE_LOGIN_FOR_USERCENTER.equals(intent.getAction())) {
//                LogUtil.d(TAG, "登陆");
//                user_state = SharedPreferencesUtil.getInstance().getUserState();
//                setTabSelection(USER);
//            }
        }
    }

    /**
     * 清除掉所有的选中状态。
     */
    private void clearSelection() {
        homepageTv.setSelected(false);
        purchasePlanTv.setSelected(false);
        purchasePriceTv.setSelected(false);
        centerRolePurchasePlanTv.setSelected(false);
        leadRoleExamineAndApproveListTv.setSelected(false);
    }

    private void hideFragments(FragmentTransaction transaction) {
        if (purchasePlanFragment != null) {
            transaction.hide(purchasePlanFragment);
        }
        if (homeFragment != null) {
            transaction.hide(homeFragment);
        }
        if (purchasePriceFragment != null) {
            transaction.hide(purchasePriceFragment);
        }
        if (centerRolePurchasePlanFragment != null) {
            transaction.hide(centerRolePurchasePlanFragment);
        }
        if (leadRoleExamineAndApproveListFragment != null) {
            transaction.hide(leadRoleExamineAndApproveListFragment);
        }

    }

    private HomeFragment getHomeFragment(FragmentTransaction transaction) {
        HomeFragment fragment = HomeFragment.getInstance();
        transaction.add(R.id.content, fragment, HomeFragment.class.getSimpleName());
        return fragment;
    }

    private PurchasePlanFragment getPurchasePlanFragment(FragmentTransaction transaction) {
        PurchasePlanFragment fragment = PurchasePlanFragment.getInstance();
        transaction.add(R.id.content, fragment, PurchasePlanFragment.class.getSimpleName());
        return fragment;
    }

    private PurchasePriceFragment getPurchasePriceFragment(FragmentTransaction transaction) {
        PurchasePriceFragment fragment = PurchasePriceFragment.getInstance(0);
        transaction.add(R.id.content, fragment, PurchasePriceFragment.class.getSimpleName());
        return fragment;
    }


    private CenterRolePurchasePlanFragment getCenterRolePurchasePlanFragment(FragmentTransaction transaction) {
        CenterRolePurchasePlanFragment fragment = CenterRolePurchasePlanFragment.getInstance();
        transaction.add(R.id.content, fragment, CenterRolePurchasePlanFragment.class.getSimpleName());
        return fragment;
    }

    private LeadRoleExamineAndApproveListFragment getLeadRoleExamineAndApproveListFragment(FragmentTransaction transaction) {
        LeadRoleExamineAndApproveListFragment fragment = LeadRoleExamineAndApproveListFragment.getInstance();
        transaction.add(R.id.content, fragment, LeadRoleExamineAndApproveListFragment.class.getSimpleName());
        return fragment;
    }

    class ExitReceiver extends BroadcastReceiver {

        @Override
        public void onReceive(Context context, Intent intent) {
            exitPorgress();
        }

    }

}
